package com.simple.editor.ui;

import com.simple.editor.callback.CallbackListener;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * {@link InfoPane} provides "information" panel on the bottom of the app.
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vlad
 * Date: 6/14/13
 * Time: 8:35 AM
 * To change this template use File | Settings | File Templates.
 */
public class InfoPane extends JPanel implements CallbackListener {
    private final BlockingQueue<Info> infos;
    private final JLabel text;

    public InfoPane() {
        infos = new LinkedBlockingDeque<Info>();
        setPreferredSize(new Dimension(500, 20));
        setBorder(BorderFactory.createMatteBorder(1, 1, 1, 2, Color.LIGHT_GRAY));
        text = new JLabel("Open project with <Ctrl-O>");
        text.setFont(new Font("Verdana", Font.ITALIC, 12));
        setLayout(new BorderLayout());
        text.setForeground(Color.GRAY);
        text.setBackground(new Color(224, 224, 224));
        text.setOpaque(true);

        add(text, BorderLayout.CENTER);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        final Info info = infos.take();
                        EventQueue.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                text.setText(info.text);
                                text.setForeground(info.infoType == InfoType.ERROR ? Color.RED : Color.GRAY);
                            }
                        });
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

    @Override
    public void addInfo(final String info) {
        infos.add(new Info(info, InfoType.INFO));
    }

    @Override
    public void addError(String error) {
        infos.add(new Info(error, InfoType.ERROR));
    }

    private enum InfoType {
        INFO, ERROR
    }

    private static class Info {
        private final String text;
        private final InfoType infoType;

        private Info(final String text, final InfoType infoType) {
            this.text = text;
            this.infoType = infoType;
        }
    }
}
